package com.hmy.contract.common.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import lombok.experimental.UtilityClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

import java.util.Date;
import java.util.Objects;

/**
 * @author seven.qi 齐胜南
 * @version 1.0
 * @description
 * @date 2023/12/26 15:30
 */
@UtilityClass
public class CommonCodeGenerator {
    public String getNextCode(RedisTemplate<String, Object> redisTemplate, String prefix, String cacheCode) {
        String currentDate = DateUtil.format(new Date(), DatePattern.createFormatter("yyMMdd"));
        RedisAtomicLong aLong = new RedisAtomicLong(cacheCode + currentDate, Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        long andIncrement = aLong.getAndIncrement();
        if (andIncrement == 0) {
            andIncrement = aLong.getAndIncrement();
        }
        //当天过期
        aLong.expireAt(DateUtil.endOfDay(new Date()));
        return prefix + currentDate + String.format("%04d", andIncrement);
    }
}
